/**
 * 吸顶效果，固钉效果
 */

import React, { Component } from 'react'
import styles from './index.module.scss'

export default class Affix extends Component {
  placeholderRef = React.createRef()
  contentRef = React.createRef()

  onScroll = () => {
    // 获取占位的div，离顶部屏幕的间距
    const { top } = this.placeholderRef.current.getBoundingClientRect()

    if (top <= 0) {
      this.contentRef.current.classList.add(styles.fixed)
      this.placeholderRef.current.style.height = '40px'
    } else {
      this.contentRef.current.classList.remove(styles.fixed)
      this.placeholderRef.current.style.height = '0px'
    }
  }

  componentDidMount () {
    window.addEventListener('scroll', this.onScroll)
  }

  // 有添加监听者，就要移除，防止泄漏内存
  componentWillUnmount () {
    window.removeEventListener('scroll', this.onScroll)
  }

  render () {
    return (
      <div>
        {/* 占位的div，刚开始高度为0，当内容吸顶上去脱离标准流以后高度变为内容的高度，
        把盒子撑起来，防止脱标下面的元素顶上去被挡住 */}
        <div ref={this.placeholderRef} id='1111'></div>
        {/* 内容的div ,children要吸顶谁就把谁包起来*/}
        <div ref={this.contentRef}>{this.props.children}</div>
      </div>
    )
  }
}